//
//  UserManager.m
//  YoucApp
//
//  Created by Liam on 12-10-16.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "UserManager.h"
#import "CmnFunc.h"
#import "YoucApi.h"
#import "YoucApiKeys.h"
#import "YAReqUserRegister.h"
#import "UserViewController.h"
#import "Util.h"
#import "UIAlertView+Modal.h"
#import "YAReqPutDeviceToken.h"
#import "APNSManager.h"
#import "YAReqUserUpdateInfo.h"

#define KEEP_SESSION_TIMEOUT	20*60

@interface UserLoginInfo : YARespUserLogin

@end

@implementation UserLoginInfo

@end

@interface UserManager()

@property (nonatomic, retain) NSString *tmpPassword;
@property (nonatomic, retain) UserLoginInfo *userLoginInfo;
@property (nonatomic, retain) id loginTask;
@property (nonatomic, retain) NSTimer *keepSessionTimer;

- (BOOL)doLogin;
- (void)clearPassword;

@end


@implementation UserManager

@synthesize tmpPassword;
@synthesize userLoginInfo = _userLoginInfo;
@synthesize isLoginLoading = _isLoginLoading;
@synthesize loginTask = _loginTask;
@synthesize userInfo = _userInfo;
@synthesize keepSessionTimer = _keepSessionTimer;
@synthesize isUserLogined;

OBJC_IMPL_SINGLETON(UserManager);

- (id)init
{
	if (self = [super init])
	{
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(invalidSessionNotification:)
													 name:YAInvalidSessionNotification object:nil];
	}
	
	return self;
}

- (void)dealloc
{
	SAFE_RELEASE(_loginTask);
	SAFE_RELEASE(_userLoginInfo);
	SAFE_RELEASE(_userInfo);
	SAFE_RELEASE(_keepSessionTimer);
	[super dealloc];
}

UserViewController *g_userViewController = nil;

+ (UserViewController *)getUserViewController
{
	if (!g_userViewController)
	{
		g_userViewController = [[UserViewController alloc] init];
	}
	
	if ([g_userViewController isViewLoaded])
		return nil;
	
	return g_userViewController;
}

- (void)invalidSessionNotification:(NSNotification *)notification
{
	[self performSelectorOnMainThread:@selector(doAutoLogin) withObject:nil waitUntilDone:NO];
}

- (BOOL)presentLogin:(UIViewController *)viewController
{
	BOOL bRet = NO;
	
	UserViewController * userViewController = [UserManager getUserViewController];
	
	if (viewController && userViewController)
	{
		userViewController.delegate = self;
		
		userViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
		userViewController.modalPresentationStyle = UIModalPresentationFullScreen;
		
		[viewController presentModalViewController:userViewController animated:YES];
		bRet = YES;
	}
	return bRet;
}

- (BOOL)isUserLogined
{
    return (self.userLoginInfo.session != nil);
}

- (void)keepSession
{
	if ([self isUserLogined])
	{
		YAReqWithSession *reqSession = [[[YAReqWithSession alloc] init] autorelease];
		
		[self fillObjectWithSession:reqSession];
		
		[[YoucApi instance] userKeepSession:reqSession context:nil delegate:self];
	}
}

- (void)setUserLoginInfo:(UserLoginInfo *)userLoginInfo
{
	SAFE_RELEASE(_userLoginInfo);
	_userLoginInfo = [userLoginInfo retain];
	if (_userLoginInfo)
	{
		[self.keepSessionTimer invalidate];
		self.keepSessionTimer = [NSTimer scheduledTimerWithTimeInterval:KEEP_SESSION_TIMEOUT target:self selector:@selector(keepSession) userInfo:nil repeats:YES];
	}
	else
	{
		[self.keepSessionTimer invalidate];
		self.keepSessionTimer = nil;
	}
}

- (BOOL)doAutoLogin
{
	if (self.isLoginLoading)
		return NO;
	
	NSString *loginName = [self getSavedLoginName];
	NSString *password = [self getSavedPassword];
	
	BOOL bRet = NO;
	
	if (password == nil)
	{
		password = self.tmpPassword;
	}
	
	if (loginName && [loginName length] && password && [password length])
	{
		[UserManager getUserViewController];
		[self userLogin:loginName password:password];
		bRet = YES;
	}
	
	return bRet;
}

- (BOOL)showLogin
{
	UIViewController *viewController = [Util rootViewController];
	BOOL bRet = [self presentLogin:viewController];
	return bRet;
}

- (BOOL)canLogin
{
	if (self.isLoginLoading)
		return NO;
	
	// 取消之前可能的自动登录
	if (self.loginTask)
	{
		[[YoucApi instance] cancelTask:self.loginTask];
		self.loginTask = nil;
	}
	
	return YES;
}

- (BOOL)doLogin
{
	if (![self canLogin])
		return NO;
    
    if (!self.isUserLogined)
    {
		_isLoginLoading = [self showLogin];
		
		if (_isLoginLoading)
			CFRunLoopRun();
    }
	
	return self.isUserLogined;
}

- (BOOL)checkUserLogin
{
	if (![self canLogin])
		return NO;
    
    if (!self.isUserLogined)
    {
		_isLoginLoading = YES;

//		UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"登录"
//														 message:@"需要登录"
//														delegate:nil
//											   cancelButtonTitle:@"取消"
//											   otherButtonTitles:@"确定", nil] autorelease];
//		
//		if ([alert showModal] == 1)
//		{
			_isLoginLoading = [self showLogin];
//		}
//		else
//		{
//			_isLoginLoading = NO;
//		}
		
		if (_isLoginLoading)
			CFRunLoopRun();
    }
	
	return self.isUserLogined;
}

- (void)userRegister:(NSString *)userAccount password:(NSString *)password nickname:(NSString *)nickname
{
	YAReqUserRegister *reqUserRegister = [[[YAReqUserRegister alloc] init] autorelease];
	reqUserRegister.userAccount = userAccount;
	reqUserRegister.password = password;
	reqUserRegister.rePassword = password;
	reqUserRegister.nickname = nickname;
	
	[self saveTempPassword:password];
	
	self.loginTask = [[YoucApi instance] userRegister:reqUserRegister context:reqUserRegister delegate:self];
}

- (void)userLogin:(NSString *)userAccount password:(NSString *)password
{
	YAReqUserLogin *reqUserLogin = [[[YAReqUserLogin alloc] init] autorelease];
	reqUserLogin.userAccount = userAccount;
	reqUserLogin.password = password;
	
	[self saveTempPassword:password];
	
	self.loginTask = [[YoucApi instance] userLogin:reqUserLogin context:reqUserLogin delegate:self];
}

- (void)updateUserInfo:(YAObjUserInfo *)userInfo
{
	BOOL needUpdate = NO;
	
	if (self.userInfo == nil)
	{
		needUpdate = YES;
	}
	else if (userInfo && (![self.userInfo.nickname isEqualToString:userInfo.nickname] ||
			[self.userInfo.sex isEqualToString:userInfo.sex] ||
			[self.userInfo.sign isEqualToString:userInfo.sign] ||
			[self.userInfo.location isEqualToString:userInfo.location] ||
			[self.userInfo.photo isEqualToString:userInfo.photo]))
	{
		needUpdate = YES;
	}
	
	if (needUpdate)
	{
		self.userInfo = userInfo;
		YAReqUserUpdateInfo *reqUserUpdateInfo = [[[YAReqUserUpdateInfo alloc] init] autorelease];
		[self fillObjectWithSession:reqUserUpdateInfo];
		reqUserUpdateInfo.userInfo = self.userInfo;
		[[YoucApi instance] userUpdateInfo:reqUserUpdateInfo context:reqUserUpdateInfo delegate:self];
	}
}

- (void)doLogout
{
	//[[CloudAPI instance] userLogout:nil];
	
	[self clearPassword];
	
	_isLoginLoading = NO;
	
	[[NSNotificationCenter defaultCenter] postNotificationName:UMUserLogoutDidFinishedNotification object:nil userInfo:nil];
}

- (void)fillObjectWithSession:(id)object
{
	if ([object respondsToSelector:@selector(setUserId:)])
	{
		[object setUserId:self.userLoginInfo.userId];
	}
	
	if ([object respondsToSelector:@selector(setSession:)])
	{
		[object setSession:self.userLoginInfo.session];
	}
}

- (void)saveLoginName:(NSString *)loginName
{
	NSString *savedLoginName = [self getSavedLoginName];
	if (savedLoginName && ![savedLoginName isEqualToString:loginName])
	{
		//[Util clearAppData];
	}
	
	[CmnFunc SaveProperty:loginName forKey:KEY_USERACCOUNT];
}

- (void)savePassword:(NSString *)password
{
	[CmnFunc SaveProperty:password forKey:KEY_PASSWORD];
}

- (void)saveTempPassword:(NSString *)password
{
	self.tmpPassword = password;
}

- (void)clearPassword
{
	[self savePassword:nil];
	[self saveTempPassword:nil];
	self.userLoginInfo = nil;
	self.userInfo = nil;
}

- (NSString *)getSavedLoginName
{
	return [CmnFunc GetPropertyWithKey:KEY_USERACCOUNT];
}

- (NSString *)getDisplayLoginName
{
	NSString *displayLoginName = [self getSavedLoginName];
	return displayLoginName;
}

- (NSString *)getLoginUserId
{
	return self.userLoginInfo.userId;
}

- (NSString *)getSavedPassword
{
	return [CmnFunc GetPropertyWithKey:KEY_PASSWORD];
}

- (void)postMainLoginDidFinishedNotification:(YARespUserLogin*)respUserLogin
{
	if (![NSThread isMainThread])
	{
		[self performSelectorOnMainThread:@selector(postMainLoginDidFinishedNotification:) withObject:respUserLogin waitUntilDone:NO];
		
		return;
	}
	
	if (respUserLogin && [respUserLogin.error code] == YoucApiErrorSuccess)
	{
		if (!self.userLoginInfo)
		{
			self.userLoginInfo = [[[UserLoginInfo alloc] init] autorelease];
		}
		
		[self saveLoginName:respUserLogin.userAccount];
		self.userLoginInfo.userAccount = respUserLogin.userAccount;
		self.userLoginInfo.session = respUserLogin.session;
		self.userLoginInfo.userId = respUserLogin.userId;
		
		// 注册 APNS
		[[APNSManager instance] openAPNS];
		
		YAReqWithSession *reqSession = [[[YAReqWithSession alloc] init] autorelease];
		
		[self fillObjectWithSession:reqSession];
		
		[[YoucApi instance] userGetInfo:reqSession context:nil delegate:self];
	}
	else
	{
		self.userLoginInfo = nil;
	}
	
	self.loginTask = nil;
	
	[[NSNotificationCenter defaultCenter] postNotificationName:UMUserLoginDidFinishedNotification object:respUserLogin userInfo:nil];

}

- (void)processUserGetInfoResponse:(YARespUserInfo *)respUserInfo
{
	if (![NSThread isMainThread])
	{
		[self performSelectorOnMainThread:@selector(processUserGetInfoResponse:) withObject:respUserInfo waitUntilDone:NO];
		
		return;
	}
	
	if ([self.userLoginInfo.userId isEqualToString:respUserInfo.userInfo.userId])
	{
		if ([respUserInfo.error code] == YoucApiErrorSuccess)
		{
			self.userInfo = respUserInfo.userInfo;
			
			[[NSNotificationCenter defaultCenter] postNotificationName:UMGetUserInfoDidFinishedNotification object:self.userInfo userInfo:nil];
		}
	}
}

#pragma mark YADelegateUser
- (void)userLoginResponse:(id)task respUserLogin:(YARespUserLogin *)respUserLogin
{
	if (self.loginTask == task && [respUserLogin.error code] != YoucApiErrorUserCancelled)
	{
		[self postMainLoginDidFinishedNotification:respUserLogin];
	}
}

- (void)userGetInfoResponse:(id)task respUserInfo:(YARespUserInfo *)respUserInfo
{
	[self processUserGetInfoResponse:respUserInfo];
}

#pragma mark UserViewControllerDelegate

- (void)userViewControllerWillDisappear:(UserViewController *)userViewController
{
	CFRunLoopStop(CFRunLoopGetCurrent());
}

- (void)userViewControllerDidDisappear:(UserViewController *)userViewController
{
	userViewController.view = nil;
	_isLoginLoading = NO;
}

@end
